﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CAD.Service
{
    public static class JsonHelper
    { 
        #region Newtonsoft Json

        /// <summary>
        /// 适用于 最外层为列表或者单体的json文档读取  
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonData"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static IList<T> ToEntity<T>(this string jsonData, JsonSerializerSettings settings = null) where T : class
        {
            IList<T> results = new List<T>();
            object obj = JsonConvert.DeserializeObject(jsonData, settings);
            if (obj is JArray)
            {
                JArray jArray = JArray.Parse(jsonData);
                foreach (var arr in jArray)
                {
                    results.Add(JsonConvert.DeserializeObject<T>(arr.ToString()));
                }
            }
            else
            {
                results.Add(JsonConvert.DeserializeObject<T>(jsonData, settings));
            }
            return results;
        }


        public static JObject ReadAllFileJson(this string jsonFile, JsonSerializerSettings settings)
        {
            try
            {
                //var setting = new JsonSerializerSettings
                //{
                //    ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
                //};
                string jsonData = File.ReadAllText(jsonFile);
                JObject jObject = JsonConvert.DeserializeObject<JObject>(jsonData, settings);
                return jObject;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 读取JSON文件
        /// </summary>
        public static JObject ReadFileJson(this string jsonFile)
        {
            try
            {
                using (System.IO.StreamReader file = System.IO.File.OpenText(jsonFile))
                {
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        JObject jObject = (JObject)JToken.ReadFrom(reader);
                        return jObject;
                    }
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public static IEnumerable<JObject> ReadListFileJson(this string jsonFile)
        {
            try
            {
                List<JObject> jObjects = new List<JObject>();
                using (System.IO.StreamReader file = System.IO.File.OpenText(jsonFile))
                {
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        foreach (var jItem in JToken.ReadFrom(reader))
                        {
                            JObject jObject = (JObject)jItem;
                            jObjects.Add(jObject);
                        }
                        return jObjects;
                    }
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }
 

        public static string ReadFileText(this string jsonFile, Encoding encoding)
        {
            try
            {
                string text = "";
                FileStream fs = new FileStream(jsonFile, FileMode.Open, FileAccess.Read);
                using (StreamReader file = new StreamReader(fs, encoding))
                {
                    text = file.ReadToEnd();
                }
                return text;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 写入JSON文件
        /// </summary>
        /// <param name="jsonFile"></param>
        /// <param name="jObject"></param>
        public static void WriteJsonTo(this JObject jObject, string jsonFile)
        {
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(jsonFile))
            {
                file.Write(jObject.ToString());
            }
        }

        /// <summary>
        /// 写入文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="jsonFile"></param>
        /// <returns></returns>
        public static string WriteJsonTo<T>(this T entity, string jsonFile) where T : class
        {
            string jsonStr =  ToJsonStr(entity);
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(jsonFile))
            {
                file.Write(jsonStr);
            }
            return jsonStr;
        }

        /// <summary>
        /// 转为字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static string ToJsonStr<T>(this T entity) where T : class
        {
            string jsonStr = JsonConvert.SerializeObject(entity).ConvertJsonString();
            return jsonStr;
        }



        //public static string FormatJsonStr(this string str)
        //{
        //    //return JsonConvert.SerializeObject(str,  Formatting.Indented);
        //    //JObject.ToString()方法会内部调用格式化，所以直接使用即可
        //    string json = str.Trim();
        //    //判读是数组还是对象
        //    if (json.StartsWith("["))
        //    {
        //        JArray jobj = JArray.Parse(str);
        //        str = jobj.ToString();
        //    }
        //    else if (json.StartsWith("{"))
        //    {
        //        JObject jobj = JObject.Parse(str);
        //        str = jobj.ToString();
        //    }
        //    return str;
        //}

        /// <summary>
        /// 格式化json字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ConvertJsonString(this string str)
        {
            //格式化json字符串
            JsonSerializer serializer = new JsonSerializer();
            TextReader tr = new StringReader(str);
            JsonTextReader jtr = new JsonTextReader(tr);
            object obj = serializer.Deserialize(jtr);
            if (obj != null)
            {
                StringWriter textWriter = new StringWriter();
                JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Newtonsoft.Json.Formatting.Indented,
                    Indentation = 4,
                    IndentChar = ' '
                };
                serializer.Serialize(jsonWriter, obj);
                return textWriter.ToString();
            }
            else
            {
                return str;
            }
        }

        /// <summary>
        /// 对JSON文件写入文本
        /// </summary>
        /// <param name="jsonFile"></param>
        /// <param name="jsonData"></param>
        public static void WriteText(this string jsonFile, string jsonData)
        {
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(jsonFile))
            {
                file.Write(jsonData);
            }
        }

     
        #endregion



    }
}
